<?php

namespace App\Services\Api;

use App\Models\GoodsIntegralChangeRecord;
use App\Models\GoodsIntegralUsable;
use App\Models\GoodsIntegralUsableInfo;
use App\Services\Admin\SystemSet;
use Illuminate\Support\Facades\DB;
use App\Models\Goods;
use App\Models\GoodsOrder;
use App\Models\UserSubscribe;
use App\Models\GoodsIntegralExpire;
use Illuminate\Support\Facades\Log;

class GoodsServices
{
    public function buy_goods($user_id, $goods_id, $goods_price)
    {
        $goods_order_id = (new GoodsOrder)->insert([
            'user_id' => $user_id,
            'goods_id' => $goods_id,
            'use_integral' => $goods_price,
            'created_at' => date("Y-m-d H:i:s"),
        ]);

        (new Goods())->where('id', $goods_id)->decrement('stock');

        $integral_format = $this->integral_format($user_id);

        foreach ($integral_format as $v) {
            $expire_insert = [];

            if($v['goods_integral_usable_total'] > $goods_price){
                $expire_insert['value'] = $goods_price;
            }else{
                $expire_insert['value'] = $v['goods_integral_usable_total'];

                GoodsIntegralUsable::where('id', $v['id'])->update(['state' => 2]);
            }

            $expire_insert['g_id'] = $v['id'];
            $expire_insert['status'] = 1;
            $expire_insert['order_id'] = $goods_order_id;
            $expire_insert['time'] = date("Y-m-d H:i:s");

            (new GoodsIntegralUsableInfo())->insert($expire_insert);

            $goods_price -= $v['goods_integral_usable_total'];

            if($goods_price <= 0)break;
        }
    }


    /**
     * 积分汇总
     * @param $user_id
     * @param $recent_day         //查詢最近多少天得汇总
     * @return mixed
     */
    public function user_goods_integral($user_id)
    {
        $goods_info = GoodsIntegralUsable::where('user_id', $user_id)->where('state', '1')->get();

        $sum_info = (new GoodsIntegralUsableInfo())->whereIn('g_id', $goods_info->pluck('id')->toArray())->sum('value');

        //查询可用积分
        return bcsub($goods_info->sum('integral'), $sum_info);
    }

    /**
     * 操作积分记录
     * @param int $integral     本次剩余积分
     * @param int $use_integral 操作积分记录
     * $param int $type  1 添加  2 扣减  3过期作废
     * $param string $reason  理由
     * $param int $user_id  用户id
     */
    public static function goods_record($use_integral = 0, $type = 0, $reason = '', $user_id = 0)
    {
        if(empty($user_id))$user_id=auth()->user('api')->id;
        $insert['user_id'] = $user_id;
        $insert['integral'] = (new GoodsServices())->user_goods_integral($user_id);
        $insert['chage_type'] = $type;
        $insert['original_id'] = 0;
        $insert['expire_time'] = SystemSet::goods_integral_expire();
        $insert['use_integral'] = $use_integral;
        $insert['reason'] = $reason;
        $insert['created_at'] = date('Y-m-d H:i:s');

        (new GoodsIntegralChangeRecord())->insert($insert);
    }

    /**
     * 处理是否过期
     */
    public function handle_expire_time($user_id = 0)
    {
        $integral_format = $this->integral_format($user_id);

        foreach ($integral_format as $v) {
            if (!empty($v['expire_time'])) {
                //判断是否已过期
                if ($v['expire_time'] < date("Y-m-d H:i:s")) {
                    $expire_insert = [];
                    $expire_insert['g_id'] = $v['id'];
                    $expire_insert['status'] = 2;
                    $expire_insert['value'] = $v['goods_integral_usable_total'];
                    $expire_insert['time'] = date("Y-m-d H:i:s");

                    (new GoodsIntegralUsableInfo())->insert($expire_insert);

                    //已用完
                    GoodsIntegralUsable::where('id', $v['id'])->update(['state' => 2]);
                }

            }
        }
    }

    /**
     * 积分处理数据格式化
     */
    public function integral_format($user_id = 0)
    {
        $goods_info = GoodsIntegralUsable::where('user_id', $user_id)->where('state', '1')->orderBy('expire_time','asc')->get();

        $sum_info = (new GoodsIntegralUsableInfo())->whereIn('g_id', $goods_info->pluck('id')->toArray())->get();

        $format = [];

        foreach ($goods_info as $v){
            $info_total = 0;

            foreach ($sum_info as $vv) {
                if ($vv->g_id == $v->id) {
                    $info_total += $vv->value;
                }
            }

            if ($v->integral != $info_total) {
                $info_total_cut = bcsub($v->integral, $info_total);

                $input['goods_integral_usable_total'] = $info_total_cut;
                $input['id'] = $v->id;
                $input['expire_time'] = $v->expire_time;

                $format[] = $input;
            }
        }

        return $format;
    }

    /**
     * 签到逻辑过滤判断
     * @param string $subscribe
     * @throws \Exception
     */
    public function sign_train_bool($subscribe = '')
    {
        if (empty($subscribe)) throw new \Exception('没有预约记录');

        if ($subscribe->subscribe_status != 2) throw new \Exception('已签到了');

        $time = date("Y-m-d H:i:s");
        $w = date("N");
        $w_string = ['一', '二', '三', '四', '五', '六', '日'][$subscribe->class_base_info->getOriginal('class_week') - 1];

        if ($subscribe->class_base_info->getOriginal('class_week') != $w) throw new \Exception("請先到周{$w_string}才來簽到");

        $qr_data = request()->input('qr_data');

        if (empty($qr_data)) throw new \Exception('qr_data必传');

        $qr_data = json_decode($qr_data, true);

        if ($time < $subscribe->class_base_info->quarterly->start_time) throw new \Exception("簽到時間還沒到開始上課季節");

        if ($time > $subscribe->class_base_info->quarterly->end_time) throw new \Exception("簽到時間已過上課季節");

        if (date("Y-m-d") != date("Y-m-d", strtotime($qr_data['time']))) throw new \Exception('不是當天');

        if ($qr_data['base_info_id'] != $subscribe->class_base_info_id) throw new \Exception('不是本节课堂');

        if ($time >= $subscribe->end_time) throw new \Exception('时辰已过,不能签到');
    }

    /**
     * 商品积分获取
     * @param $user_id
     * @param $subscribe_id
     * @throws \Exception
     */
    public function add_goods_integral($user_id, $subscribe_id)
    {

        $userSubscribeObj = UserSubscribe::where('id', $subscribe_id)->first();

        if ($userSubscribeObj->subscribe_status == 2) {

            $new_data = [
                'user_id' => $user_id,
                'subscribe_id' => $subscribe_id,
                //'user_integral__change_recode_id'=>0,
                'integral' => $userSubscribeObj->use_integral,
                'remarks' => '签到獲得',
                'state' => 1,
                'created_at' => date("Y-m-d H:i:s"),
            ];

            $res = GoodsIntegralUsable::insert($new_data);

        }
    }
}
